<template>
  <div class="container">
    <div style="with: 100%">
      标题：<el-input :disabled="isdisabled === 'true' || isdisabled === true" style="margin: 10px 0" v-model="title" placeholder="请输入标题" />
      <div class="type">
        类型：<el-select  clearable :disabled="isdisabled === 'true' || isdisabled === true"  v-model="type" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <Toolbar v-if="isshowtools === 'true' || isshowtools === true" style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="simple" />
      <Editor style="height: 500px; overflow-y: hidden" v-model="valueHtml" :defaultConfig="editorConfig" mode="simple" @onCreated="handleCreated" @customPaste="customPaste" />
      <el-button v-if="isshowtools === 'true' || isshowtools === true" type="primary" @click="submit">提交</el-button>
      <el-button v-if="isshowtools === 'true' || isshowtools === 'false'" type="default" @click="router.back()">返回</el-button>
    </div>
  </div>
</template>

<script setup>
// 富文本编辑器文档链接: https://www.wangeditor.com/v5/getting-started.html
// 引入富文本编辑器CSS
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import {createarticle, searchticlebyid} from "../apis/artic";
// 导入富文本编辑器的组件
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import axios from "axios"
import { useRoute, useRouter } from 'vue-router';
const options = ref([
  {label: '学习笔记', value: '学习笔记'},
  {label: '随便写写', value: '随便写写'},
  {label: '技术杂烩', value: '技术杂烩'}
])
onMounted(()=>{
  if (route.query._id) {
    console.log(route.query, '123');
    isshowtools.value = route.query.isshowtools
    isdisabled.value = route.query.isdisabled
    _id.value = route.query._id
    searchbyid()
    console.log(isshowtools.value, 'isshowtoolsonMounted');
  }
})
const router = useRouter()
const route = useRoute()
const title = ref('')
const type = ref('')
const valueHtml = ref('');
let _id = ref('')
let isshowtools = ref(true)
let isdisabled = ref(false)
console.log(isshowtools.value, 'isshowtools');
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {};
const editorConfig = ref({ placeholder: '请输入内容...', MENU_CONF: {} });
const searchbyid = ()=>{
  let param = {
    _id:_id.value
  }
  console.log(param, 'param');
  searchticlebyid(param).then(res=>{
    if (res.data.isok) {
      title.value = res.data.data[0]?.title
      type.value = res.data.data[0]?.type
      valueHtml.value = res.data.data[0]?.content || '<p>hello word!</p>'
    }
  })
}
// 自定义图片上传
editorConfig.value.MENU_CONF['uploadImage'] = {
  maxNumberOfFiles: 10,
  allowedFileTypes: ['image/*'],
  async customUpload(file, insertFn) {
    console.log('上传图片', file);
    let formData = new FormData();
    formData.append('file', file);
    let res = await axios.post('http://8.130.21.251:3001/upload-img', formData);
    console.log(res.data, 'res.data');
    if (res.data.isok) {
      // url 为服务器返回的图片链接地址
      const url = res.data.data.url;
      const alt = res.data.data.name;
      const href = res.data.data.href;
      // 这里的file为上传的图片对象,insertFn传入
      insertFn(url, alt, href);
    }
  },
  // 单个文件上传成功之后
    onSuccess(file, res) {  
      console.log(`${file.name} 上传成功`, res)
    },
    // 单个文件上传失败
    onFailed(file, res) {   
      console.log(`${file.name} 上传失败`, res)
    },
    // 上传错误，或者触发 timeout 超时
    onError(file, err, res) {       
      console.log(`${file.name} 上传出错`, err, res)
    }
}
// 富文本编辑器生成后触发
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  console.log(isdisabled, 'isabled');
  if (isdisabled.value === 'true' || isdisabled.value === true) {
    editorRef.value.disable()
  }
  console.log(editorConfig.value.MENU_CONF, 'editorConfig.value');
};
// 监听富文本编辑器粘贴行为
const customPaste = (editor, event, callback) => {
  // 获取粘贴的纯文本
  const text = event.clipboardData.getData('text/plain');
  if (text) {
    editor.insertText(text);
    event.preventDefault();
    callback(false);
  }
};
const submit = () => {
  if (title.value !== '' && editorRef.value.getHtml() + '' !== '<p><br></p>' && type.value !== '') {
    const text = {
      content: editorRef.value.getHtml() + '',
      title: title.value,
      type: type.value
    }
    console.log('dianjile submit', editorRef.value.getHtml());
    createarticle(text).then((res)=>{
      console.log(res.data, 'data', text)
      if (res.data.isok) {
        ElNotification({
          title: 'Success',
          message: '提交成功',
          type: 'success'
        })
        router.push('/articlist')
      }
    })
  } else {
    ElMessage({
      message: '文章标题,类型和内容不能为空！',
      type: 'error',
    })
  }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="less" scoped>
.container{
  padding: 40px;
  background-color: #fff;
}
.el-select{
  width: 12.5rem;
}

</style>